use std::{fs, io::{BufReader, prelude::*}, net::{TcpListener, TcpStream}, time::Duration};

use web_server::ThreadPool;

fn main() {
    println!("Starting server...");
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4);
    println!("Server started, waiting for connections...");

    for stream in listener.incoming().take(2) {
        let stream = stream.unwrap();
        println!("Got connection, executing request...");

        pool.execute(|| {
            handle_connection(stream);
        });
    }

    println!("Shutting down.");
}

fn handle_connection(mut stream: TcpStream) {
    // 设置读取超时
    if let Err(_) = stream.set_read_timeout(Some(Duration::from_secs(5))) {
        println!("Failed to set read timeout");
        return;
    }
    
    let buf_reader = BufReader::new(&mut stream);
    let request_line = match buf_reader.lines().next() {
        Some(Ok(line)) => line,
        Some(Err(_)) => {
            println!("Failed to read request line");
            return;
        }
        None => {
            println!("No request line received");
            return;
        }
    };
    println!("Request: {}", request_line);

    let (status_line, filename) = match &request_line[..] {
        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "index.html"),
        _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
    };

    let contents = fs::read_to_string(filename).unwrap();
    let length = contents.len();

    let response = format!("{}\r\nContent-Length: {}\r\n\r\n{}", status_line, length, contents);

    stream.write_all(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}
